package BinaryTree;

//从前序与中序遍历序列构造二叉树 : https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
class SolutionCreateTree {

    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public int preIndex ;
    public TreeNode buildTree(int[] preorder, int[] inorder) {

        return buildTreeChilde(preorder,inorder,0,inorder.length-1);

    }

    private TreeNode buildTreeChilde(int[] preorder,int[] inorder,int inbegin,int inend) {

        if(inbegin > inend) {
            return null;//没有 左树 或者 没有 右树 
        }

        TreeNode root = new TreeNode(preorder[preIndex]);

        int rootIndex = findIndexRoot(inorder,inbegin,inend,preorder[preIndex]);
        if(rootIndex == -1) {
            return null;
        }

        preIndex++;

        root.left = buildTreeChilde(preorder,inorder,inbegin,rootIndex-1);

        root.right = buildTreeChilde(preorder,inorder,rootIndex+1,inend);
        
        return root;

    }

    private int findIndexRoot(int[] inorder,int inbegin, int inend,int key) {

        for(int i = inbegin; i <= inend;i++) {
            if(inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }


}